import web, os, sys, json
web.config.debug = False # will not work with sessions
import ConfigParser # for working directory specific settings        
import hashlib # this is useful to encrypt hashes in password validation and storage


config = ConfigParser.RawConfigParser()
# todo: find a reliable way of reading files from a central directory
config.read('config.cfg')


topUrl = config.get('app_settings', 'topUrl')
sessionsDir = config.get('app_settings', 'sessionsDir')
appDb = config.get('app_settings', 'appDb')


"""
specify URL dispatching
"""
urls = (
    '/', 'hello',
    '/cars','cars',
    '/users','users',
    '/vendors', 'vendors',
    '/cars/gas','gasPurchase',
    '/environment.*', 'environment',
    )


class hello:
    def GET(self):
        """
        a simple front page greeting
        perhaps include some usage information
        """
        return "Welcome to Cars"
        
class users:
    def GET(self):
        """
        a list of all users
        """
        pass

    def POST(self):
        """
        CREATE TABLE users 
        (uid integer primary key asc not null, username text, password text);
        """
        pass

class cars:
    def GET(self):     
        # get the current cars
        db = web.database(dbn='sqlite', db=appDb)
        allCars = db.select('cars')
        data = []
        for car in allCars:
            data.append(car)  

        web.header('Content-type:', 'application/json')
        return json.dumps(data) 

    def POST(self):
        """ 
        process a new car to submit     
            CREATE TABLE cars 
            (cid integer primary key asc not null, carname text unique, 
            make text, model text, year integer); 
        """      
        post_input = web.input()
        db = web.database(dbn='sqlite', db=appDb)
        if post_input.carname and post_input.make and post_input.model and post_input.year:
            success = db.insert('cars', carname=post_input.carname, make=post_input.make, model=post_input.model, year=post_input.year)   
            if success:
                response = "data insert successful"
                return response 
            else:
                return "?????"
        else:
            return "the car name, make, model and year inputs must not be empty!"  


class vendors:
    def GET(self):
        """
        returns a list of vendors in the database
        content type is json
        """
        db = web.database(dbn="sqlite", db=appDb)
        vendors = db.select('vendors')
        data = []
        for vendor in vendors:
            data.append(vendor)

        web.header('Content-type:', 'application/json')
        return json.dumps(data)         

    def POST(self):
        """ 
        process a new vendor to insert into database
        return nothing if succesful
        throw exception if otherwise

        CREATE TABLE vendors 
            (vid integer primary key asc not null, vendorname text unique, 
             address text, city text, state text, zipcode text, category text);

        """
        post_input = web.input()
        db = web.database(dbn='sqlite', db=appDb)
        if post_input.vendorname and post_input.address and post_input.city and post_input.state and post_input.zipcode:
            success = db.insert('vendors', vendorname=post_input.vendorname, address=post_input.address, city=post_input.city, state=post_input.state, zipcode=post_input.zipcode, category=post_input.category)   
            if success:
                return "data insert successful"
            else:
                return "?????"
        else:
            return "the vendor name, address, city, state and zipcode inputs must not be empty!"
 
 

class gasPurchase:
    def GET(self):
        """
        return gas purchase records
        content type is json
        """
        web_input = web.input()    
        db = web.database(dbn="sqlite", db=appDb)
        if not web.input():
            gasPurchases = db.select('gas')
        else:
            sql = 'select * from gas where car = {} order by gid {} limit 0,{}'.format(web_input.carid, web_input.sort, web_input.rows)
            gasPurchases = db.query(sql)
        data = []
        for gp in gasPurchases:
            data.append(gp)

        web.header('Content-type:', 'application/json')
        return json.dumps(data)         

    def POST(self):              
        """
        read post data
        process and insert into database
        CREATE TABLE gas 
            (gid integer primary key asc not null, car integer, gallons text, 
             odometer text, milesTraveled text, vendor text, 
             ppg text, bill text, ts datetime);
        """
        post_input = web.input()
        db = web.database(dbn='sqlite', db=appDb)
        if post_input.carid and post_input.bill and post_input.gallons and post_input.odometer and post_input.milesTraveled and post_input.ppg:
            success = db.insert('gas', car=post_input.carid, gallons=post_input.gallons, odometer=post_input.odometer, milesTraveled=post_input.milesTraveled, vendor=post_input.vendor, ppg=post_input.ppg, bill=post_input.bill, ts=post_input.ts)   
            if success:
                return "data insert successful"
            else:
                return "?????"
        else:
            return "the bill, odometer, miles traveled, ppg and gallons inputs must not be empty!"



class environment:
    def GET(self):
        """
        returns a simple table
        containing server's environmental specifications
        """

        environment = web.ctx.env
        resource = "<table>"
        for k in environment.keys():
            resource += "<tr><th style='text-align: right;'>" + k + "</th><td>" + str(environment[k]) + "</td></tr>"
        resource += "</table>"
        return resource

"""
run the application from python directly
using WSGI, and not through Apache using mod_wsgi
"""
if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
